var eventObj = require("../event");
var fs = require("fs");
var _ = require("underscore");

function TramStatus(options){
    this.tramCode = options.tramCode || '1001';
    this.serviceNum = "0";
    //该车所有相关的运行计划信息
    this.runPlan = options.runPlan || null;
    //时间游标
    this.passTimeBySec = options.initTimeBySec;
    this.startTimeBySec = options.initTimeBySec+15;
    this.lineCode;             //线路号
    this.latitude;             //纬度
    this.longtitude;           //经度
    this.direct = options.direct;             //上下行
    this.fromTerminus;         //上一站站台
    this.toTerminus;           //下一站站台
    this.distance = 0;           //距前方车站的距离
    this.mileage = 0;             //里程
    this.speedLimit;          //限速值
    this.speed = 0;               //速度
    this.soonerOrLater;       //早晚点信息
    this.arrivingTime;           //到站时间
    this.driverCode = 3000;           //驾驶员编号
    this.isInline = true;     //是否在线
    this.runPercent;          //已运行区间百分比
    this.Length ;         //电车长度
    this.end ;               //是否停止服务
    this.tramIp;                 //车辆IP
    this.totalLength = options.totalLength||0;      //车辆总里程

    this.currentSegment;       //当前车头所在区段
    this.runDistance = 3;          //当前车头所在区段越过的距离
    this.status = "offline";

    //停车所需相关参数
    this.stopArgs = {
        isStop : false,
        waitTime : 0,
        reentryFlag: false
    };
    this.packetNum = 0  //车辆发包序号
    //---------------------------- 用于判断车辆是否刚进入区段 或 离开区段的属性
    this.runExecutor = options.runExecutor||null;
    this.currentSegmentIndex = 0;
    //保存正线segment的数组
    this.segmentArr = [];
    //保存section数组
    this.sectionArr = [];
    //保存section-segment对应关系数组
    this.sectionSegmentArr = [];
    //保存当前路由
    this.currentRoute = null;
    this.avgStopTime = options.runPlan.avgStopTime;
    this.avgSpeed = options.runPlan.avgSpeed;
    this.isReached = 1;
    this.firstRun = true;
    this.allowToStart = true;
    this.driveMode = 0;//待机数据
    //模拟开始时间游标，初始为0
    this.startDuration = 0;
    this.isReadyStart = true;
    //模拟折返时间游标，初始为0
    this.reentryDuration = 0;
    this.isReentryStart = false;
    //是否接收到车载参数包
    this.isGetTramArgs = false;
}

module.exports = TramStatus;

TramStatus.prototype.init = function(){
    //在大循环中只运行一次,配置基本参数
    var $this = this;
    $this.status = "offline";
    $this.mileage = 0;
    $this.lineCode = 1;
    $this.currentSegmentIndex = 1;
    $this.createSegmentArrData();
    $this.createSectionArrData();
    $this.createSectionSegmentArrData();

    $this.currentSegment = $this.getSegment($this.currentSegmentIndex);
    $this.currentSection = $this.getSection();
    $this.distance = $this.currentSection.Length;
    $this.fromTerminus = $this.currentSection.from_terminus;
    $this.toTerminus = $this.currentSection.to_terminus;
    $this.runDistance = 0;
  //  $this.driveMode = 19;
    $this.totalLength = 0;
    $this.stopArgs.isStop = true;
    $this.isReadyStart = true;
    $this.serviceNum = "0";
}

TramStatus.prototype.run = function(){
   var $this = this;
   if($this.firstRun){
      $this.firstRun = false;
   }else{
      if ($this.passTimeBySec >= $this.runPlan.startTime) {
          if($this.isReadyStart){
            $this.mockStartOperation();
            return;
          }
          if($this.isReentryStart){
            $this.mockReentryOperation();
            return;
          }
          if ($this.stopArgs.isStop) {
            $this.waitForStart();
          }else {
            $this.move(); 
          }
          $this.status = "online";
     }else{
        console.log('waiting for the tram to start');
    }   
    $this.passTimeBySec += 2;          
   }       
}

/*停站等待*/
TramStatus.prototype.waitForStart = function(){
    var $this = this;
    $this.speed = 0;
    //当车辆驶出第一个segment时
    if ( $this.stopArgs.waitTime >= $this.avgStopTime) {
        $this.start();
        $this.isReached = 0;
    }else{
        $this.currentSegment = $this.getSegment($this.currentSegmentIndex);
        $this.currentSection = $this.getSection();
        $this.fromTerminus = $this.currentSection.from_terminus;
        $this.toTerminus = $this.currentSection.to_terminus;
        $this.distance = $this.currentSection.Length;
       // $this.speed = 30;
        $this.isReached = 1;
        $this.stopArgs.waitTime += $this.runExecutor.updateInterval;
    }
}

/*车辆移动*/
TramStatus.prototype.move = function(){
    //通过判断车辆
    var $this = this;
    $this.driveMode = 1;
   // $this.speed = 30;
    $this.speed = $this.avgSpeed;
    //var  next = $this.currentSegment.getNext($this.direct);
    var next = $this.getSegment($this.currentSegmentIndex + 1);
    //判断位移是否越过当前区段
    if(next){
        if (($this.runDistance + Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval)) <= $this.currentSegment.Length) {
            $this.runDistance += Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval);
            $this.mileage += Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval);
            $this.distance = $this.currentSection.Length - $this.mileage;
            //在正线运行时记录总里程数据
            $this.totalLength +=  Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval);
            $this.isReached = 0;
        }else{
            //计算车辆越过当前区段进入下一区段
            $this.mileage += Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval);
            $this.currentSegmentIndex ++;
            $this.isReached = 0;
            if($this.mileage >= $this.currentSection.Length){
                //马上进入到停车状态,进入到下一区间模式
                console.log($this.currentSegmentIndex);
                $this.stop();
                $this.speed = 0;
                $this.runDistance = 0;
                $this.totalLength += $this.currentSection.Length - ($this.mileage - Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval));
                $this.mileage = 0;
                $this.distance = 0;
            }else{
                //此处overDistance逻辑有问题 待验证
                var overDistance = ($this.runDistance + Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval)) - $this.currentSegment.Length;
                $this.runDistance = overDistance;
                $this.currentSegment = next;
                $this.distance = $this.currentSection.Length - $this.mileage;
                if($this.distance < 0){
                    $this.distance = 0;
                }
                $this.totalLength +=  Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval);
            }

        }
    }else{
        if (($this.runDistance + Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval)) <= $this.currentSegment.Length) {
            $this.runDistance += Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval);
            $this.mileage += Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval);
            $this.totalLength += Math.round($this.avgSpeed/3.6*$this.runExecutor.updateInterval);
            $this.distance = $this.currentSection.Length - $this.mileage;
            $this.isReached = 0;
        }else{
            //进入到折返模式
            $this.isReached = 1;
            //$this.stopArgs.reentryFlag = true;
            if($this.stopArgs.waitTime < 15){
                $this.stopArgs.waitTime += $this.runExecutor.updateInterval;
                $this.totalLength += $this.distance;
                $this.distance = 0;
                $this.speed = 0;
                return;
            }
            if($this.stopArgs.waitTime <= $this.avgStopTime && $this.stopArgs.waitTime >= 15){
                $this.stopArgs.waitTime += $this.runExecutor.updateInterval;
              //  $this.totalLength += $this.distance;
                $this.distance = 0;
                //$this.runDistance = 0;
                $this.speed = 0;
                if($this.direct ==='down'){
                    $this.fromTerminus = "211";
                    $this.toTerminus = "211";
                }else{
                    $this.fromTerminus = "227";
                    $this.toTerminus = "227";
                }
            }else{
               // $this.serviceNum++;
                $this.stopArgs.waitTime = 0;
                $this.isReentryStart = true;
             //   $this.serviceNum = "0";

            }

        }

    }

}



//需要模拟车辆在开始阶段过程，此段逻辑要经历一段时间，
//此段时间前大部分为待机模式，后一部分为正常模式，在正常模式时，到站状态经历从false变true的过程
/*
TramStatus.prototype.mockStartOperation = function(){
    //前4分钟模拟待机状态数据,到站状态为false
    var $this = this;
    $this.startDuration += 2;
    if(!$this.isGetTramArgs){
        $this.driveMode = 0;//待机模式
        $this.isReached = false;
    }else if($this.startDuration < 10){
       $this.driveMode = 1;
       $this.isReached = false;
    }else{
        $this.startDuration = 0;
        $this.isReadyStart = false;
    }
    
     
}*/

//需要模拟车辆在开始阶段过程，此段逻辑要经历一段时间，
//此段时间前大部分为待机模式，后一部分为正常模式，在正常模式时，到站状态经历从false变true的过程
TramStatus.prototype.mockStartOperation = function(){
    //前4分钟模拟待机状态数据,到站状态为false
    var $this = this;
    $this.startDuration += 2;
    if($this.startDuration <= 15){
        $this.driveMode = 0;//待机模式
        $this.isReached = false;
    }else if($this.startDuration > 15 && $this.startDuration <= 30){
       $this.driveMode = 1;
       $this.isReached = false;
    }else{
        $this.startDuration = 0;
        $this.isReadyStart = false;
    }
    
     
}

//模拟折返操作，一直保持待机状态，从末站开出后方向先保持不变,维持一段时间后改变方向
TramStatus.prototype.mockReentryOperation = function(){
    var $this = this;
    $this.reentryDuration += 2;
    if ($this.reentryDuration <= 30) {
        $this.driveMode = 0;
        $this.isReached = false;
    }else{
        $this.isReentryStart = false;
        $this.reentryDuration = 0;
        $this.direct == "up"?$this.direct="down":$this.direct="up";
        $this.isGetTramArgs = false;
        $this.init();
    }

}

//发送车载状态包
TramStatus.prototype.sendStatusEventInfo = function(serviceNum){
    var $this = this;
    var tempobj = {
        "tramCode" : $this.tramCode,
        "currentSegment" : $this.currentSegment,
        "runDistance" : $this.runDistance,
        "direct" : $this.direct,
        "speed" : $this.speed,
        "lineCode" : $this.lineCode,
        "serviceNum" : $this.serviceNum,
        "distance": $this.distance,
        // "mileage" : $this.mileage,
        "totalLength" : $this.totalLength,
        "fromTerminus" : $this.fromTerminus,
        "toTerminus" : $this.toTerminus,
        "driverNum" : $this.driverCode,
        "packetNum" : $this.packetNum,
        "totalLength" : $this.totalLength,
        "isStop" : $this.stopArgs.isStop,
        "isReached": $this.isReached,
        "driveMode": $this.driveMode
    }
    console.log(tempobj);
    $this.packetNum ++;
    return tempobj;

}

TramStatus.prototype.stop = function(){
    this.stopArgs.isStop = true;
    this.stopArgs.waitTime = 0;
}

TramStatus.prototype.start = function(){
    var $this = this;
    $this.stopArgs.isStop = false;
    $this.stopArgs.waitTime = 0;
    $this.isReached = 0;
    console.log("isReached::::::"+ $this.isReached);
}

TramStatus.prototype.reset = function(){

}

TramStatus.prototype.online = function(){
    this.status = "online";
}

TramStatus.prototype.offline = function(){
    this.status = "offline";
}

TramStatus.prototype.isOnline = function(){
    return "online" === this.status;
}

TramStatus.prototype.createSegmentArrData = function(){
    var $this = this;
    var segmentData = eval("(" + fs.readFileSync("./datas/segment.json", "utf-8")+ ")");
    if($this.segmentArr.length > 0){
        $this.segmentArr.splice(0,$this.segmentArr.length-1);
    }
    if($this.direct == 'down'){
        $this.segmentArr = _.filter(segmentData.rows,function(e){
            return e.direct ==="down"
        })
    }else{
         $this.segmentArr = _.filter(segmentData.rows,function(e){
            return e.direct ==="up"
        })
    }

}

TramStatus.prototype.createSectionArrData = function(){
    var $this = this;
    var sectionData = eval("(" + fs.readFileSync("./datas/section.json", "utf-8")+ ")");
    $this.sectionArr = sectionData.rows;
}

TramStatus.prototype.createSectionSegmentArrData = function(){
    var $this = this;
    var sectionSegmentData = eval("(" + fs.readFileSync("./datas/section_segment.json", "utf-8")+ ")");
    $this.sectionSegmentArr = sectionSegmentData.rows;
}


//将正线所需的segments绑定到this对象
TramStatus.prototype.getSegmentsForRoute = function(currentRoute){
    var $this = this;
    if($this.segmentArr.length > 0){
        $this.segmentArr.splice(0,$this.segmentArr.length-1);
    }
    if ($this.startSegmentCode) {
        //首先需要在路径中找到该segment元素
        var item = null;
        _.forEach(currentRoute.routeItems,function(e){
            if (e.itemCode === $this.startSegmentCode) {
                item = e;
            };
        });
        var index = _.indexOf(currentRoute.routeItems,item);
        var restRouteItems = _.rest(currentRoute.routeItems,index);
        $this.segmentArr = _.filter(restRouteItems,function(e){
            return e.type ==="segment"
        })
        //此处条件只进入一次
        $this.startSegmentCode = null;
    }else{
        $this.segmentArr = _.filter(currentRoute.routeItems,function(e){
            return e.type ==="segment"
        })
    }

}
//根据游标获取当前segment
TramStatus.prototype.getSegment = function(index){
      var $this = this;  
      if (_.isNaN(index)||index < 0) {
         return null;
      };    
     // var segmentCode = $this.segmentArr[index].itemCode;
      var currentSegment = $this.segmentArr[index-1];
      return currentSegment; 

}
//根据当前游标获取当前section
TramStatus.prototype.getSection = function(){
    var $this = this;
    var sectionId = null;
    var currentSection = null;
    if ($this.currentSegment != null) {
       _.forEach($this.sectionSegmentArr,function(ele){
         if(ele.segment_id === $this.currentSegment.id){
            sectionId = ele.section_id;
         }
       })
    }
    if(sectionId != null){
      _.forEach($this.sectionArr,function(ele){
         if(ele.id === sectionId){
            currentSection = ele;
         }
       })
    }
    return currentSection;
}




